<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :xs="24" :sm="12">
            <a-form-model-item label="编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.code" disabled placeholder="请输入编号"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs" v-show="model.id">
      <a-tab-pane tab="材料价格执行表明细" :key="refKeys[0]" :forceRender="true">
        <a-row>
          <!-- 新增 -->
          <a-col :span="12">
            <a-space>
              <a-button type="primary" icon="PlusCircleOutlined" size="large" @click="addMadial"> 新增 </a-button>
            </a-space>
          </a-col>
        </a-row>
        <a-table
          bordered
          ref="table"
          :data-source="dataSource"
          tableLayout="fixed"
          :columns="bussMaterialPriceDetailTable.columns"
          :rowKey="
            (record) => {
              return record.rowKey
            }
          "
          :pagination="false"
          :scroll="{ x: 1500, y: 500 }"
        >
        <template slot="supplierId" slot-scope="text, record">
          <tsl-material-supplier :materialId="record.materialId" :rowData="record" v-model="record.supplierId" @handlerOk="handleSupplierChange"/>
          </template>
          <template slot="taxPrice" slot-scope="text, record">
            <edit-number-cell-2 :text="text" @change="onCellChange(record, 'taxPrice', $event)"></edit-number-cell-2>
          </template>
          <template slot="noTaxPrice" slot-scope="text, record">
            <edit-number-cell-2 :text="text" @change="onCellChange(record, 'noTaxPrice', $event)"></edit-number-cell-2>
          </template>
          <template slot="freight" slot-scope="text, record">
            <edit-number-cell-2 :text="text" @change="onCellChange(record, 'freight', $event)"></edit-number-cell-2>
          </template>
          <template slot="price" slot-scope="text, record">
            <edit-number-cell-2 :text="text" @change="onCellChange(record, 'price', $event)"></edit-number-cell-2>
          </template>
          <template slot="operation" slot-scope="text, record">
            <a-space>
              <!--                <a @click="handleEdit(record)">编辑</a>-->
              <a-popconfirm title="确认删除?" @confirm="() => onDelete(record)">
                <a href="javascript:;">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </a-table>
      </a-tab-pane>
    </a-tabs>
    <erp-goods-supplier-list-model ref="selectGoodsList"
                    :category="category"
                    @goodsOk="goodsOk"
                    checkval="checkbox"/>

  </a-spin>
</template>

<script>
import { FormTypes, getRefPromise, VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin'

import { getAction, httpAction, postAction, putAction } from '@api/manage'
import { initDictOptions } from '@/components/dict/JDictSelectUtil'
import EditableCell2 from '@/components/table/EditableCell2.vue'
import EditNumberCell2 from '@/components/table/EditNumberCell2.vue'
import ErpGoodsSupplierListModel from './ErpGoodsSupplierListModel.vue'
import TslMaterialSupplier from '@/components/tsl/cell/TslMatSupplier.vue'

export default {
  name: 'BussMaterialPriceForm',
  mixins: [JVxeTableModelMixin],
  components: {
    EditableCell2,
    EditNumberCell2,
    ErpGoodsSupplierListModel,
    TslMaterialSupplier,
  },
  data() {
    return {
      supplierOptions:[],
      tax: 1.13,
      visible: false,
      category:'4',
      ipagination: {
        current: 1,
        pageSize: 5,
        pageSizeOptions: ['5', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      model: {
        code: '',
      },
      validatorRules: {},
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      refKeys: ['bussMaterialPriceDetail'],
      tableKeys: ['bussMaterialPriceDetail'],
      activeKey: 'bussMaterialPriceDetail',
      dataSource: [],
      // 原料价格执行表明细
      bussMaterialPriceDetailTable: {
        loading: false,
        columns: [
          {
            title: '#',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function (t, r, index) {
              return parseInt(index) + 1
            },
          },

          {
            title: '物料编号',
            dataIndex: 'materialCode',
            width: '120',
          },
          {
            title: '物料名称',
            dataIndex: 'materialName',
            width: '200',
          },
          {
            title: '规格',
            dataIndex: 'spec',
            width: '100',
          },
          {
            title: '供应商/生产厂家',
            dataIndex: 'supplierId',
            scopedSlots: { customRender: 'supplierId' },
            ellipsis: true,
            width: '300',
          },
          {
            title: '出厂价格',
            children: [
              {
                title: '含税价格',
                dataIndex: 'taxPrice',
                width: 150,
                scopedSlots: { customRender: 'taxPrice' },
              },
              {
                title: '不含税价格',
                dataIndex: 'noTaxPrice',
                width: 150,
                scopedSlots: { customRender: 'noTaxPrice' },
              },
            ],
          },
          {
            title: '运费',
            dataIndex: 'freight',
            width: 150,
            scopedSlots: { customRender: 'freight' },
          },
          {
            title: '本月价格',
            dataIndex: 'price',
            width: 150,
            scopedSlots: { customRender: 'price' },
          },
          // {
          //   title: '原料id',
          //   dataIndex: 'materialId',
          // },
          {
            title: '操作',
            dataIndex: 'operation',
            fixed: 'right',
            width: 150,
            scopedSlots: { customRender: 'operation' },
          },
        ],
      },
      url: {
        add: '/material/price/bussMaterialPrice/add',
        edit: '/material/price/bussMaterialPrice/edit',
        supplierList:'/base/erpGoodsSupplier/list',
        bussMaterialPriceDetail: {
          list: '/material/price/bussMaterialPrice/queryBussMaterialPriceDetailByMainId',
        },
      },
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    this.initDictConfig()
    getAction(this.url.supplierList).then(res=>{
      console.log("供应商列表：",res);
      this.supplierOptions=res.result.records;
      console.log("供应商列表：",this.supplierOptions);
    })
  },
  methods: {
    initDictConfig() {
      //初始化字典 --配置项
      initDictOptions('tsl_config').then((res) => {
        if (res.success) {
          console.log(res.result)
          let item = res.result.filter((t) => t['text'] == "原材料税率")
          if (item && item.length > 0) {
            console.log(item, '获取原材料税率：', item[0]['value'])
            this.tax = Number.parseFloat(item[0]['value'])
          }
        }
      })
    },
    getSequenceNum() {
      let url = '/sys/fillRule/executeRuleByCode/price_execute_code'
      putAction(url, {}).then((res) => {
        // 执行成功，获取返回的值，并赋到页面上
        if (res.success) {
          this.model.code = res.result
        }
      })
    },
    handleSupplierChange(data){
      console.log("修改供应商",data)
      const dataSource = [...this.dataSource]

      const target = dataSource.find(
        (item) => item.rowKey === data.row.rowKey
      )
        target.supplierId=data.value;

        target.rowKey = target.rowKey + 1
        this.dataSource = dataSource
        console.log(this.dataSource);
    },
    onCellChange(record, dataIndex, value) {
      this.$set(record, dataIndex, value)
      if (dataIndex != 'noTaxPrice') {
        record.noTaxPrice = (Number.parseFloat(record.taxPrice) / this.tax).toFixed(2)
        console.log(record.noTaxPrice, 'noTaxPrice')
      }
      record.price = Number.parseFloat(record.noTaxPrice) + Number.parseFloat(record.freight)
      const dataSource = [...this.dataSource]

      const target = dataSource.find(
        (item) => item.materialId === record.materialId && item.supplierId === record.supplierId
      )
      if (record) {
        target[dataIndex] = value
        target.noTaxPrice = record.noTaxPrice
        target.price = record.price
        target.rowKey = target.rowKey + 1
        this.dataSource = dataSource
      }
    },
    addMadial() {
      this.$nextTick(() => {
        this.$refs.selectGoodsList.add()
      })
    },
    goodsOk(data) {
      if (data.length > 20) {
        this.$message.warning('一次只能添加二十条')
        return
      }

      if(data && data.length>0){

        const dataSource = [...this.dataSource]
        const _this=this;
        console.log("选择物料供应商：",data,data.length);
        data.forEach(function (item, index) {
          console.log(item,"item",index)
          let detail = {}
            detail.rowKey =  dataSource.length+1+Math.random()
            detail.materialId = item.id
            detail.materialCode = item.code
            detail.materialName = item.name
            detail.spec = item.noneSpec
            detail.supplierId = item.supplierId
            detail.supplierName = item.supplierName
            detail.priceId = _this.model.id
            dataSource.push(detail)
        })
        this.dataSource=dataSource;
      }
    },
    handleEdit() {},

    onDelete(record) {
      const dataSource = [...this.dataSource]
      this.dataSource = dataSource.filter((item) => item !== record)
      // if(this.model.details || this.model.details.length == 0){
      //   this.supplier = {};
      // }
    },
    addBefore() {
      this.dataSource = []
      this.getSequenceNum()
    },
    getAllTable() {
      let values = this.tableKeys.map((key) => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      this.$nextTick(() => {})
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        // this.requestSubTableData(this.url.bussMaterialPriceDetail.list, params, this.bussMaterialPriceDetailTable)
        getAction(this.url.bussMaterialPriceDetail.list, params).then((res) => {
          if (res.success) {
            this.dataSource = res.result.records || res.result
            this.dataSource = this.dataSource.map((item) => {
              return { ...item, rowKey: item.id }
            })
            console.log(this.dataSource)
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
          } else {
            this.$message.warning(res.message)
          }
        })
      }
    },
    //校验所有一对一子表表单
    validateSubForm(allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([])
          .then(() => {
            resolve(allValues)
          })
          .catch((e) => {
            if (e.error === VALIDATE_NO_PASSED) {
              // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
            } else {
              console.error(e)
            }
          })
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)

      return {
        ...main, // 展开
        bussMaterialPriceDetailList: allValues.tablesValue[0].values,
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
    close() {
      this.visible = false
      this.$emit('close')
      this.$refs.form.clearValidate()
    },
    submitForm() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          this.$set(this.model, 'bussMaterialPriceDetailList', this.dataSource)
          httpAction(httpurl, this.model, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
  },
}
</script>

<style scoped></style>
